const { where } = require('sequelize');
const { blogModel } = require('../models/model/blog');
const { messageModel } = require('../models/model/message');
const { dataToJSON, dataDeleteOrUpdateRes } = require('../utils/tools');

// 添加
exports.createService = async (data) => {
	const result = await messageModel.create(data);
	return dataToJSON(result, '');
};

// 删除
exports.removeService = async (id) => {
	const result = await messageModel.destroy({
		where: { id }
	});
	return dataDeleteOrUpdateRes(result);
};

// 通过文章id删除
exports.removeByBlogIdService = async (id) => {
	const result = await messageModel.destroy({ where: { blogId: id } });
	return dataDeleteOrUpdateRes(result);
};

// 查
exports.findAll = async (query) => {
	const size = Number(query.size) || 1;
	const limit = Number(query.limit) || 10;
	const params = {
		limit,
		offset: (size - 1) * limit,
		where: {
			blogId: query.blogId || null
		},
		include: [
			{
				model: blogModel,
				attributes: ['id', 'title', 'description', 'scanNumber', 'commentNumber'],
				as: 'blog' // 存放查询出数据的 key
			}
		]
	};

	const { count, rows } = await messageModel.findAndCountAll(params);
	return JSON.parse(
		JSON.stringify({
			total: count,
			rows
		})
	);
};

// 通过id查找
exports.findByIdService = async (id) => {
	const result = await messageModel.findOne({ where: { id } });
	return dataToJSON(result, '');
};
